package com.zhiyou100.interceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.zhiyou100.model.Admin;
import com.zhiyou100.model.User;

public class AdminInterceptor implements HandlerInterceptor{

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		HttpSession session = request.getSession();
		Object o = session.getAttribute("admin");
		if(o==null) {

			Cookie[] coo = request.getCookies();
			String login_name = null;
			String login_pwd = null;
			User user = null;
			for (Cookie cookie : coo) {
				if(cookie.getName().equals("login_name")) {
					login_name = cookie.getValue();
				}
				if(cookie.getName().equals("login_pwd")) {
					login_pwd = cookie.getValue();
				}
			}
			if(login_name!=null&&login_pwd!=null) {
				//模拟从数据库匹配账号和密码
				Admin admin = new Admin();
				admin.setLogin_name(login_name);
				admin.setLogin_pwd(login_pwd);
				request.getSession().setAttribute("admin", admin);
				return true;
			}else {
				System.out.println("你还没有登录");
				response.sendRedirect(request.getServletContext().getAttribute("BaseContext")+"front/index.jsp");
			}

		}else {
			System.out.println("用户已经登录");
			return true;
		}
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}

}
